#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@File    ：book_repo.py
@Author  ：平
@Date    ：2025/10/2 21:23 
"""
from app.config.config import Session
from app.model.book import Book


def edit_book(book_id, book: dict) -> Book:
    with Session() as session:
        with session.begin():
            existing_book = session.query(Book).filter(Book.id == book_id).first()
            if existing_book:
                update_data = {key: value for key, value in book.items() if value is not None}
                for key, value in update_data.items():
                    if hasattr(existing_book, key):
                        setattr(existing_book, key, value)
        session.refresh(existing_book)
    return existing_book


def query_by_mix_book(id:int,title:str) -> list[Book]:
    with Session() as session:
        query = session.query(Book)
        if id is not None:
            query = query.filter(Book.id == id)
        if title is not None:
            query = query.filter(Book.title.like(f"%{title}%"))
        return query.all()
